import 'dart:io';

import 'package:path_provider/path_provider.dart';

import '../public.dart';

/// 我的页面
class SettingPage extends StatefulWidget {
  SettingPage({Key key}) : super(key: key);

  @override
  _SettingPageState createState() {
    return _SettingPageState();
  }
}

class _SettingPageState extends State<SettingPage> {
  ThemeProvider theme;
  UserProvider user;
  UserRecordProvider userRecord;
  String _cacheSizeStr;

  @override
  void initState() {
    super.initState();
    loadCache();
  }

  @override
  Widget build(BuildContext context) {
    theme = Provider.of<ThemeProvider>(context);
    user = Provider.of<UserProvider>(context);
    userRecord = Provider.of<UserRecordProvider>(context);
    return Scaffold(
        backgroundColor: theme.primaryColor,
        appBar: AppBar(
          title: Text('设置'),
          leadingWidth: 44,
          leading: BackComponent(),
        ),
        body: SingleChildScrollView(
            child: Padding(
                padding: EdgeInsets.only(left: 16, right: 16),
                child: Column(children: [
                  MenuComponent(
                    title: '清除缓存',
                    decoration: BoxDecoration(),
                    rightWidgets: [
                      Text(
                        '${_cacheSizeStr ?? '0K'}',
                        style: TextStyle(
                            color: ColorUtil.rgba(255, 255, 255, 0.6)),
                      )
                    ],
                    onTap: _clearCache,
                  ),
                  MenuComponent(
                    title: '相关协议',
                    hasIconArrow: false,
                    rightWidgets: [
                      _agreements('《隐私政策》', onTap: () {
                        Routers.navigateTo(RouterPage.WEB,
                            params: {'url': ACGN.config.ysxy});
                      }),
                      _agreements('《用户协议》', onTap: () {
                        Routers.navigateTo(RouterPage.WEB,
                            params: {'url': ACGN.config.userAgreement});
                      })
                    ],
                  ),
                  user.data.type != 'device'
                      ? Container(
                          margin: EdgeInsets.only(top: 40, bottom: 20),
                          child: FlatButton(
                              onPressed: _logout,
                              height: 48,
                              minWidth: double.infinity,
                              textColor: ColorUtil.rgba(255, 255, 255, 0.6),
                              shape: RoundedRectangleBorder(
                                  side: BorderSide.none,
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(24))),
                              color: ColorUtil.rgba(255, 255, 255, 0.05),
                              child: Text(
                                '退出登录',
                                style: TextStyle(fontSize: 18),
                              )),
                        )
                      : SizedBox(
                          height: 20,
                        ),
                  Text(
                    '当前版本1.0.1',
                    style:
                        TextStyle(color: ColorUtil.rgba(255, 255, 255, 0.25)),
                  )
                ]))));
  }

  void _logout() {
    user.deleteUserInfo();
    userRecord.deleteUserRecord();
    Navigator.pop(context);
    LogUtil.v('退出登录');
  }

  Widget _agreements(String title,
      {Function onTap, EdgeInsetsGeometry padding, TextStyle style}) {
    Widget child = Text(
      title,
      style: style ?? TextStyle(color: Colors.blue[400]),
    );
    if (onTap != null) {
      child = GestureDetector(onTap: onTap, child: child);
    }
    return Container(
        padding: padding ?? EdgeInsets.only(left: 4), child: child);
  }

  ///加载缓存
  Future<Null> loadCache() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
      tempDir.list(followLinks: false, recursive: true).listen((file) {
        //打印每个缓存文件的路径
        print(file.path);
      });
      print('临时目录大小: ' + value.toString());
      setState(() {
        _cacheSizeStr = _renderSize(value);
      });
    } catch (err) {
      print(err);
    }
  }

  /// 递归方式 计算文件的大小
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        if (children != null)
          for (final FileSystemEntity child in children)
            total += await _getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }

  void _clearCache() async {
    /// 此处展示加载loading
    try {
      Directory tempDir = await getTemporaryDirectory();
      //删除缓存目录
      await delDir(tempDir);
      await loadCache();
      ACGN.toast.message('清除缓存成功');
    } catch (e) {
      print(e);
      ACGN.toast.message('清除缓存失败');
    } finally {
      // 此处隐藏加载loading
    }
  }

  /// 递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      print(e);
    }
  }

  /// 格式化文件大小
  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = []..add('B')..add('KB')..add('MB')..add('GB');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }

  void dispose() {
    super.dispose();
  }
}
